<?php
declare(strict_types=1);
namespace Hangpu888\Hpadmin\controller;

use Hangpu888\Hpadmin\Controller;
use Hangpu888\Hpadmin\model\Tags as ModelTags;
use Hangpu888\Hpadmin\utils\builder\FormBuilder;
use Hangpu888\Hpadmin\utils\builder\ListBuilder;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\validate\Tags as ValidateTags;

class Tags extends Controller
{
    /**
     * 显示列表
     *
     * @return void
     */
    public function index()
    {
        $limit = request()->get('limit',30);
        $page = request()->get('page',1);
        $list = ModelTags::order('id desc')
        ->paginate([
            'page'          => $page,
            'list_rows'     => $limit
        ])
        ->each(function($item){
            $item->tag_url = "/index/Tags/index?tag={$item->tag}";
            return $item;
        })
        ->toArray();
        $builder = new ListBuilder;
        $data = $builder
            ->addColumn('rightButtonList', '操作', [
                'type'              => 'template',
                'template'          => 'rightButtonList',
                'width'             => '180'
            ])
            ->addTopButton('add', '添加', [
                'title'             => '添加数据',
                'api'               => '/hpadmin/Tags/add',
            ])
            ->addRightButton('edit', '修改', [
                'api'               => '/hpadmin/Tags/edit',
                'title'             => '修改',
            ], [
                'type'              => 'text'
            ])
            ->addRightButton('delete', '删除', [
                'api'               => '/hpadmin/Tags/del',
                'method'            => 'delete',
                'title'             => '温馨提示',
                'content'           => '是否确认删除该数据？',
                'type'              => 'confirm',
            ], [
                'type'              => 'text'
            ])
            ->addColumn('id', '序号', [
                'width'             => '80',
            ])
            ->addColumn('ctime', '添加时间', [
                'width'             => '180',
            ])
            ->addColumn('utime', '更新时间', [
                'width'             => '180',
            ])
            ->addColumn('tag_url', '系统标签')
            ->addColumn('title', '标题名称')
            ->addColumn('view', '热门指数')
            ->setData($list['data'])
            ->setDataPage($list['total'], $list['last_page'], $list['per_page'], $list['current_page'])
            ->create();
        return Json::successRes($data);
    }

    /**
     * 显示添加表单
     *
     * @return void
     */
    public function add()
    {
        try {
            if (request()->method() == 'POST') {
                // 获取数据
                $post = request()->post();
    
                // 数据验证
                hpValidate(new ValidateTags,$post);
                if (ModelTags::where(['tag'=> $post['tag']])->count()) {
                    return Json::fail('该标签已存在');
                }
                
                // 数据操作
                $model = new ModelTags;
                foreach ($post as $field => $value) {
                    $model->$field = $value;
                }
                if ($model->save()) {
                    return Json::success('添加成功');
                } else {
                    return Json::fail('添加失败');
                }
            } else {
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('post')
                    ->addRow('title', 'input', '标题名称', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('tag', 'input', '标签名称', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('view', 'input', '热门指数', '0')
                    ->addRow('content', 'custom', '图文内容', '',[
                        'type'              => 'wangeditor'
                    ])
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 显示编辑表单
     *
     * @return void
     */
    public function edit()
    {
        $id = request()->get('id');
        $model = ModelTags::where(['id'=> $id])->find();
        try {
            if (request()->method() == 'PUT') {
                // 获取数据
                $post = request()->post();
    
                // 数据验证
                hpValidate(new ValidateTags,$post);
                $map1[] = ['id','<>',$id];
                $map1[] = ['tag','=',$post['tag']];
                if (ModelTags::where($map1)->count()) {
                    return Json::fail('该标签已存在');
                }
                
                // 数据操作
                foreach ($post as $field => $value) {
                    $model->$field = $value;
                }
                if ($model->save()) {
                    return Json::success('修改成功');
                } else {
                    return Json::fail('修改失败');
                }
            } else {
                if (!$model) {
                    return Json::fail('找不到该数据');
                }
                $info = $model->toArray();
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('put')
                    ->addRow('title', 'input', '标题名称', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('tag', 'input', '标签名称', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('view', 'input', '热门指数', '0')
                    ->addRow('content', 'custom', '图文内容', '',[
                        'type'              => 'wangeditor'
                    ])
                    ->setFormData($info)
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 删除数据
     *
     * @return void
     */
    public function del()
    {
        $id = request()->get('id');
        $model = ModelTags::where(['id' => $id])->find();
        if (!$model) {
            return Json::fail('该数据不存在');
        }
        if ($model->delete()) {
            return Json::success('删除成功');
        } else {
            return Json::fail('删除失败');
        }
    }
}
